package filter;

import Dao.UserDao;
import model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoLoginFilter",urlPatterns = "/Login.html")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.转为Http
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse) resp;
        //2.获取cookie
        Cookie[] cookies=request.getCookies();
        //3.找到ke因为autologin的cookie,并将value保存到autoLogin
        String autoLogin=null;
        if(cookies!=null)
            for(Cookie c:cookies){
                if(c.getName().equalsIgnoreCase("autoLogin")){
                    autoLogin=c.getValue();
                }
            }

        //4.判断autoLogin是否为null，为null表示没找到
        if(autoLogin!=null){
            //自动登录
            String[] user=autoLogin.split("-");
            User u=new User(user[0],user[1]);
            //boolean result=new UserDao().checkLogin(u);
            String result=new UserDao().checkLogin(u);
            if(result!=""){
                //登录成功，把用户信息保存在session中
                request.getSession().setAttribute("user",u);

                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;");
                response.setCharacterEncoding("utf-8");
                response.sendRedirect("main.html?stuNo="+result);
            }
        }
        chain.doFilter(request, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
